package com.lanqiao.attendance.controller;

import com.lanqiao.attendance.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.awt.print.Book;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: attendance
 * @description
 * @author: 刘 华
 * @create: 2022-07-22 11:54
 **/

@RestController
@RequestMapping("file")
public class FileController {


    @Value("${uploadFile.path}")
    private String  realPath;

    @PostMapping("submitImg")
    public Result submitImg(MultipartFile file, HttpServletRequest req) {
        String dir = realPath.split(":")[1];
        String path = realPath.split(":")[2];
        path = dir+":"+path; // D+:+//img

        System.out.println(path);   //D://img
        System.out.println(file);
//       给新的文件前缀命名
        String newFileName = System.currentTimeMillis() + "";
        //获取文件的原始名   xxx.jpg  or xxx.png
        String oldFileName = file.getOriginalFilename();
        //获取文件后缀 .jpg or  png
        String extension = oldFileName.substring(oldFileName.lastIndexOf("."));
        //生成新的文件名
        newFileName = newFileName + extension;
//         在该目录创建文件
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(file1, newFileName));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(666,"图片上传失败");

        }
        System.out.println(newFileName+"---------"+oldFileName);
        return Result.success("上传成功",newFileName);
    }
}
